<%@ page language="java" pageEncoding="UTF-8" %>
<%@ page 
	import="java.io.*"
	import="java.net.*"
	import="java.util.*"
	import="net.sf.json.*"
	import="com.markan.facebook.*"
	import="com.markan.facebook.utl.*"
	import="java.text.SimpleDateFormat" %>    
<%!
	public String htmlImg(String src) {
		if(src==null)
			return "";
		return "<img src='" + src + "'>";
	}
	public String htmlALink(String href, String name, String target) {
		if(href==null || name==null || name.isEmpty())
			return "";
		return "<a href='" + href + "' target='"+ target +"'>" +name + "</a>";
	}
	public String cutString(String str) {
		if( str.length() > 500 ) {
			return str.substring(0, 500)+"...";
		}
		return str;
	}
	/**
	 * 현재 날짜를 가져온다.
	 * @return
	 */
	private String geToday() {
		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		return f.format(new Date());
	}
%>	
<%
	StringBuffer sb = new StringBuffer();

	Map<String, String> nameKorMap = new HashMap<String, String>();
	nameKorMap.put("Jeong Seok Oh", "오정석");
	nameKorMap.put("ByongJin Yoon", "윤병진");

	String APP_ID = Facebook.getKeyString_inProperties("APP_ID");
	Facebook facebook = new Facebook(APP_ID, request);
	String accessToken = facebook.getAccessToken();
	
	//id
	String id = request.getParameter("id");
	
sb.append("<html>");
sb.append("<head>");
sb.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
sb.append("</head>");
sb.append("<body>");
sb.append("<table border='1' cellpadding='0' cellspacing='0' bordercolor='#808080' frame='hsides' rules='rows' style='table-layout:fixed;font-size:9pt;word-break:break-all'>");
sb.append("<thead>");
sb.append("<tr bgcolor='FFFF99'>");
sb.append("	<th rowspan='3' width='60'>B표번호</th><th rowspan='3' width='60'>테스트 시나리오 번호</th><th colspan='8'>장해사항</th><th rowspan='3' width='60'>비고</th>");
sb.append("</tr>");
sb.append("<tr bgcolor='FFFF99'>");
sb.append("	<th rowspan='2' width='200'>현상</th><th rowspan='2' width='200'>원인</th><th rowspan='2' width='200'>대책</th><th rowspan='2' width='200'>대응소스</th><th colspan='2' width='160'>발생정보</th><th colspan='2' width='160'>대응정보</th>");
sb.append("</tr>");
sb.append("<tr bgcolor='FFFF99'>");
sb.append("	<th width='80'>발생일</th><th width='60'>발견자</th><th width='80'>대응일</th><th width='60'>대응자</th>");
sb.append("</tr>");
sb.append("</thead>");
sb.append("<tbody>");

	JSONObject feedjsonObj = facebook.getProfileFeed(id);
	
	JSONArray feedDataJSONArray = MknJSONUtil.getObject2JSONArray(feedjsonObj.get("data"));
	for(int i=0, feedSize = feedDataJSONArray.size(); i<feedSize; i++ ) {
		
		sb.append("<tr>");
		
		JSONObject feedDataJsonObj = (JSONObject) feedDataJSONArray.get(i);

		String feedId = (String) feedDataJsonObj.get("id");
		String feedMessage = (String) feedDataJsonObj.get("message");
		String feedPicture = (String) feedDataJsonObj.get("picture");
		String feedLink = (String) feedDataJsonObj.get("link");
		String feedIcon = (String) feedDataJsonObj.get("icon");
		String feedObjectId = (String) feedDataJsonObj.get("object_id");
		String feedType = (String) feedDataJsonObj.get("type");							//status
		String feedCreatedTime = (String) feedDataJsonObj.get("created_time");	
		String feedUpdatedTime = (String) feedDataJsonObj.get("updated_time");	
		String aLinkUrl = "http://www.facebook.com/groups/" + feedId.replace("_", "/") + "/";	//페이스북 원문 링크
		
		//from
		JSONObject fromJsonObj = MknJSONUtil.getObject2JSONObject(feedDataJsonObj.get("from"));
		String fromId = (String) fromJsonObj.get("id");
		String fromName = (String) fromJsonObj.get("name");
		
		//댓글 영역
//		sb.append("<td>");
		//comments
		JSONObject commentsJsonObj = MknJSONUtil.getObject2JSONObject(feedDataJsonObj.get("comments"));
		int commentsCount = MknJSONUtil.getObject2Integer(commentsJsonObj.get("count"));
		JSONArray commentsJsonArray = MknJSONUtil.getObject2JSONArray(commentsJsonObj.get("data"));
		
		int commentsSize = commentsJsonArray.size();
		String commentMessages[] = new String[commentsSize];
		String commentCreatedTimes[] = new String[commentsSize];
		String commentFromNames[] = new String[commentsSize];
		
		for(int j=0; j<commentsSize; j++ ) {
			JSONObject commentDataJsonObj = MknJSONUtil.getObject2JSONObject(commentsJsonArray.get(j));
			
			String commentId = (String) commentDataJsonObj.get("id");
			commentMessages[j] = (String) commentDataJsonObj.get("message");
			commentCreatedTimes[j] = (String) commentDataJsonObj.get("created_time");
			
			//comment from
			JSONObject commentFromJsonObj = MknJSONUtil.getObject2JSONObject(commentDataJsonObj.get("from"));
			String commentFromId = (String) commentFromJsonObj.get("id");
			commentFromNames[j] = (String) commentFromJsonObj.get("name");
			
		}
		
		//------ print ----------------------------------------------------------------
		sb.append("<td align='center'>" + (i+1) + "</td><td></td>");	
		sb.append("<td>" + cutString(feedMessage).replaceAll("\n", "<br>") + "</td>");//메세지
		sb.append("<td></td>");
		sb.append("<td>");
		for(String commentMessage:commentMessages) {
			sb.append(commentMessage + "<br>");
		}
		sb.append("</td>");	
		sb.append("<td></td>");
		sb.append("<td align='center'>" + feedCreatedTime.substring(0, 10) + "</td>");	//작성일
		sb.append("<td align='center'>" + nameKorMap.get(fromName) + "</td>");										//작성자
		sb.append("<td align='center'>");
		for(String commentCreatedTime:commentCreatedTimes) {
			sb.append(commentCreatedTime.substring(0, 10) + "<br>");
		}
		sb.append("</td>");	
		sb.append("<td align='center'>");
		for(String commentFromName:commentFromNames) {
			sb.append( nameKorMap.get(commentFromName) + "<br>");
		}
		sb.append("</td>");
		sb.append("<td></td>");	
		//------ print ----------------------------------------------------------------
		
		sb.append("</tr>");
		
	} //for feedDataJSONArray
	
	
	//Paging
	JSONObject feedPagingJsonObj = MknJSONUtil.getObject2JSONObject(feedjsonObj.get("paging"));
	String feedPagingPrevios = (String) feedPagingJsonObj.get("previous");
	String feedPagingNext = (String) feedPagingJsonObj.get("next");

sb.append("</tbody>");
sb.append("</table>");
sb.append("</body>");
sb.append("</html>");

//out.print(sb.toString());

try {
	request.setCharacterEncoding("UTF-8");
	
	String filename = geToday() + ".xls";
	
	//Content-Disposition 세팅하기위해 file 이름을 변환한다.
	String convName = java.net.URLDecoder.decode(filename, "UTF-8");
	convName = filename;
	
	String dispositionPrefix = "attachment; filename=";
	String encodedFilename = null;
	
	//응답 헤더의 Content-Type을 세팅한다. 
	response.reset();
	response.setContentType("application/x-msdownload");
	//response.setContentType("application/octet-stream");
	String strClient = request.getHeader("User-Agent");
	if( strClient.indexOf("MSIE 5.5") != -1 ) {					//IE 5.5
		response.setContentType("doesn/matter;");
		encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll(" ", "_");
	} else if (strClient.indexOf("MSIE") > -1) {					//IE 6 ~ 9
		encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
	} else if (strClient.indexOf("Chrome") > -1) {			//크롬
		StringBuffer sb2 = new StringBuffer();
		for (int i = 0; i < filename.length(); i++) {
			char c = filename.charAt(i);
			if (c > '~') {
			    sb2.append(URLEncoder.encode("" + c, "UTF-8"));
			} else {
			    sb2.append(c);
			}
	    }
	    encodedFilename = sb2.toString();
	} else if (strClient.indexOf("Opera") > -1) {					//오페라
		encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
		response.setContentType("application/octet-stream;charset=UTF-8");
	} else { 																					//Firefox
		encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
	}
	response.setHeader("Content-Disposition", dispositionPrefix + encodedFilename);
	
	byte data[] = (sb.toString()).getBytes();
	response.setContentLength(data.length);
	
	
	BufferedOutputStream outs = null;
	try {
	    outs = new BufferedOutputStream(response.getOutputStream());
		outs.write(data);
	} catch (Exception ex) {
	} finally {
	    if (outs != null) { try { outs.close(); } catch (Exception ignore) { }  }
	}

} catch(Exception e) {
	log(e.toString());
} 
%>